#!/usr/bin/env python3

from graphviz import Digraph
from ..utils import fetch_url, st_get_api, icons
import networkx as nx
import json

def create_graph(topology_data):
    """Creates a Graphviz graph from the topology data."""
    dot = Digraph(comment='Network Topology')

    # Add nodes and edges based on the fetched topology
    for link in topology_data:
        src = link['src']
        dst = link['dst']
        src_dpid = str(src['dpid']).lstrip('0')
        dst_dpid = str(dst['dpid']).lstrip('0')
        src_label = f"{src['name']} ({src_dpid})"
        dst_label = f"{dst['name']} ({dst_dpid})"
        src_port = str(src['port_no']).lstrip('0')
        dst_port = str(dst['port_no']).lstrip('0')

        dot.node(src['dpid'], src_label)
        dot.node(dst['dpid'], dst_label)
        dot.edge(src['dpid'], dst['dpid'], label=f"port {src_port} to {dst_port}")

    return dot

def get_topo():
    end_point = 'v1.0/topology/links'
    url, time_out = st_get_api(end_point)
    try:
        # Fetch the topology data from the API
        topology_data = fetch_url(url, time_out)
        # Create a graph from the topology data
        dot = create_graph(topology_data)
        return topology_data, dot
    except Exception as e:
        raise

def get_topo():
    end_point = 'v1.0/topology/links'
    url, time_out = st_get_api(end_point)
    try:
        # Fetch the topology data from the API
        topology_data = fetch_url(url, time_out)
        # Create a graph from the topology data
        dot = create_graph(topology_data)
        return topology_data, dot
    except Exception as e:
        raise

def get_weighted_topo():
    end_point = 'stats/topology'
    url, time_out = st_get_api(end_point)
    try:
        # Fetch the topology data from the API
        raw = fetch_url(url, time_out)
        G = nx.readwrite.json_graph.node_link_graph(raw)
        return raw, G
    except Exception as e:
        raise

if __name__ == "__main__":
    main()
